<template>
	<view class="search-box">
		<uni-search-bar @input="input" 
		:radius="100" 
		cancelButton="none" 
		placeholder="请输入内容">
		</uni-search-bar>
		
		<!-- 搜索建议列表 -->
		<view class="sugg-list" v-if="serachResults.length !==0">
			<view class="sugg-item" v-for="(item , i) in serachResults.goods" :key="i"
				  @click="gotoDetail(item)">
				<view class="goods-name" >{{item.goods_name}}</view>
				<uni-icons type="arrowright" size=16></uni-icons>
			</view>
		</view>
		
		<!-- 搜索历史 -->
		<view class="history-box" v-else>
			<!-- 标题区域 -->
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="17" @click="clearAll"></uni-icons>
			</view>
			<!-- 历史区域 -->
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,i) in history" :key="i" @click="gotoGoodsList(item)"/>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer:null,
				keyWord:null,
				serachResults:[],
				historyList:[],
			};
		},
		methods:{
			input(e){
				//防抖处理
				clearTimeout(this.timer)
				
				this.time = setTimeout(()=>{
					this.keyWord = e
					this.getSerachList(this.keyWord)
				},1000)
			},
			async getSerachList(kw){
				if(kw.trim().length === 0){
					this.serachResults = []
					return
				}
				
				const {data:res} = await uni.$http.get("/api/public/v1/goods/search",{query:kw})
				if (res.meta.status !== 200) {
					return uni.showMsg()
				}
				
				this.serachResults = res.message
				
			},
			gotoDetail(item){
				this.historyList.push(this.keyWord)
				const set = new Set(this.historyList)
				set.delete(this.keyWord)
				set.add(this.keyWord)
				this.historyList = Array.from(set)
				uni.setStorageSync('kw',JSON.stringify(this.historyList))
				uni.navigateTo({
					url:"/subpackage/goods_detail/goods_detail?goods_id="+ item.goods_id
				})
			},
			
			clearAll(){
				uni.setStorageSync('kw','[]')
				this.historyList = []
			},
			gotoGoodsList(item){
				uni.navigateTo({
					url:"/subpackage/goods_list/goods_list?query="+ item
				})
			}
		},
		computed:{
			history(){
				return [...this.historyList].reverse()
			}
		},
		onLoad(){
			this.historyList = JSON.parse(uni.getStorageSync('kw'))
		}
	}
</script>

<style lang="scss" scoped>
.search-box{
	position: sticky;
	top: 0;
	// 如果不加z-index，则会被覆盖
	z-index: 999;
}

.sugg-list{
	padding: 0 5px;
	.sugg-item{
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding: 13px 0;
		border-bottom: 1px solid #efefef;
		.goods-name{
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
}
.history-box{
	padding: 0 5px;
	.history-title{
		display: flex;
		justify-content: space-between;
		height: 40px;
		align-items: center;
		font-size: 14px;
		border-bottom: 1px solid #efefef;
	}
	.history-list{
		display: flex;
		flex-wrap: wrap;
		.uni-tag{
			margin-top: 5px;
			margin-right: 5px;
		}
	}
}
</style>
